package band.wukong.practice.mina.quickstart.sumup;

import band.wukong.practice.mina.quickstart.sumup.codec.SumUpProtocolCodecFactory;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;

/**
 * Desc:
 * author: wukonggg@139.com
 */
public class SumupClient {

    private static final String HOSTNAME = "localhost";

    private static final int PORT = 8080;

    private static final long CONNECT_TIMEOUT = 30 * 1000L; // 30 seconds

    public static void main(String[] args) throws Throwable {
        String[] defaultArgs = new String[] {"1", "2", "3"};;
        if (args.length == 0) {
//            System.out.println("Please specify the list of any integers");
//            return;
            defaultArgs = args;
            System.out.println("Load the default args");
        }

        // prepare values to sum up
        int[] values = new int[defaultArgs.length];
        for (int i = 0; i < defaultArgs.length; i++) {
            values[i] = Integer.parseInt(defaultArgs[i]);
        }

        NioSocketConnector connector = new NioSocketConnector();

        // Configure the service.
        connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
        if (SumupServer.USE_CUSTOM_CODEC) {
            connector.getFilterChain().addLast(
                    "codec",
                    new ProtocolCodecFilter(
                            new SumUpProtocolCodecFactory(false)));
        } else {
            connector.getFilterChain().addLast(
                    "codec",
                    new ProtocolCodecFilter(
                            new ObjectSerializationCodecFactory()));
        }
        connector.getFilterChain().addLast("logger", new LoggingFilter());

        connector.setHandler(new SumupClientSessionHandler(values));

        IoSession session;
        for (; ; ) {
            try {
                ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT));
                future.awaitUninterruptibly();
                session = future.getSession();
                break;
            } catch (RuntimeIoException e) {
                System.err.println("Failed to connect.");
                e.printStackTrace();
                Thread.sleep(5000);
            }
        }

        // wait until the summation is done
        session.getCloseFuture().awaitUninterruptibly();

        connector.dispose();
    }

}
